using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using QQZiFramework;
using QQZiFramework.Mvc;
using System.Collections.Generic;
using System.Net.WebSockets;

namespace QQZiCore.Mvc
{
    public static class Extension
    {
        //public static void UseIM(this IApplicationBuilder app, IConfiguration configuration)
        //{
        //    bool isServer = false;

        //    if (configuration["IMServer:Server"] == null)
        //    {
        //        if (configuration["IMServer"] == "." || configuration["IMServer"] == "local" )
        //        {
        //            isServer = true;
        //        }
        //    }
        //    else
        //    {
        //        isServer = Convert.ToBoolean(configuration["IMServer:Server"]);
        //    }

        //    if (isServer)
        //    {
        //        app.UseWebSockets();
        //        app.Use(async (context, next) =>
        //           {
        //               bool isWebSocket = context.WebSockets.IsWebSocketRequest;
        //               if (isWebSocket)
        //               {
        //                   using (IServiceScope scope = app.ApplicationServices.CreateScope())
        //                   {
        //                       //do something 
        //                       WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
        //                       await IMDriver.ProcessWebSocketRequest(context, webSocket);
        //                   }
        //               }
        //               else
        //               {
        //                   //Hand over to the next middleware
        //                   await next();
        //               }
        //           });
        //    }
        //    else
        //    {
        //        //websocket 客户端   
        //        string wsUrl = configuration["IMServer:Url"];
        //        if (wsUrl == null)
        //        {
        //            //兼容旧的
        //            wsUrl = configuration["IMServer"];
        //        }
        //        IMDriver.SetAsClient(wsUrl);
        //    }
        //}


        public static void UserOEMMvc(this IApplicationBuilder app, int platform)
        {
            app.UseMiddleware<EndRequestMiddleware>();
            //app.UseRouting();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "empty", template: "", defaults: new { controller = "Public", action = "Index" });
                routes.MapRoute(name: "default", template: "Public/{action=Index}/{id?}", defaults: new { controller = "Public" });
                routes.MapRoute(name: "vue", template: "{OEM}/vue/{page=index}", defaults: new { controller = "Vue", action = "Index" });
                routes.MapRoute(name: "react", template: "{OEM}/react/{page=index}", defaults: new { controller = "React", action = "Index" });

                if (platform == 2)
                {
                    //routes.MapRoute(name: "areaname",template: "{Admin:exists}/{OEM}/{controller=Home}/{action=Index}/{id?}");
                    routes.MapAreaRoute(
                        name: "Admin",
                        areaName: "Admin",
                        template: "/{OEM=default}/{controller=Public}/{action=Index}"
                        );
                }
                else
                {
                    routes.MapRoute(name: "OEM", template: "{OEM}/{controller}/{action=Index}/{id?}");
                    routes.MapAreaRoute(
                        name: "Admin",
                        areaName: "Admin",
                        template: "/Admin/{OEM=default}/{controller=Public}/{action=Index}"
                        );
                }
            });
        }


        public static void UseQQZI(this IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration,Type middlewareType, int platform)
        {
            if (!string.IsNullOrEmpty(configuration["UseCors"]))
            {

                app.UseCors(builder =>
               {

                   builder.AllowAnyHeader();
                   builder.AllowAnyMethod();
                   builder.AllowCredentials();
                   if (configuration["UseCors"] == "*")
                   {
                       builder.SetIsOriginAllowed(x => true);
                   }
                   else
                   {
                       builder.WithOrigins(configuration["UseCors"].Split(','));//指定跨域URL
                   }

               });
            }

            int defaultRedisDB = string.IsNullOrEmpty(configuration["Redis:Default"]) ? 0 : Convert.ToInt32(configuration["Redis:Default"]);
            int DBIdentity = string.IsNullOrEmpty(configuration["Redis:DBIdentity"]) ? 0 : Convert.ToInt32(configuration["Redis:DBIdentity"]);

            //IMDriver.IM_Redis_Database_Index = string.IsNullOrEmpty(configuration["Redis:IM"]) ? defaultRedisDB + 2 : Convert.ToInt32(configuration["Redis:IM"]);
            DBContext.Default_Redis_Database_Index = defaultRedisDB;
            DBContext.DBIdentity_Redis_Database_Index = DBIdentity;
            QQZiFramework.Mvc.Extension.Session_Redis_Database_Index = defaultRedisDB;
            //VipProfitBLL.Agencys_Redis_Database_Index = defaultRedisDB;
            //PayAudit.Redis_PAY_Database_Index = PluginBLL.Redis_PAY_Database_Index = string.IsNullOrEmpty(configuration["Redis:PAY"]) ? defaultRedisDB : Convert.ToInt32(configuration["Redis:PAY"]);
            //QQZiFramework.MQ.RedisMQ.RedisMQ_DBINDEX = string.IsNullOrEmpty(configuration["Redis:MQ"]) ? defaultRedisDB : Convert.ToInt32(configuration["Redis:MQ"]);
            if (middlewareType == null) middlewareType = typeof(EndRequestMiddleware);
            app.UseMiddleware(middlewareType);
            //app.UserOEMMvc(platform);
            //app.UseIM(configuration);
            app.UserDBContext<OEMMemberShip>(env, configuration);

            //QQZiCore.Loader.SystemLoader.OnStart(false, platform);

            // MessageDriver.MessageServer = configuration["MessageServer"];
            // string serverDueTime = configuration["ServerDueTime"];
            // if (!String.IsNullOrEmpty(serverDueTime))
            // {
            //     MessageDriver.ServerDueTime = Convert.ToInt32(serverDueTime);
            // }
            // OEMMemberShip.Platform = platform;
            // QQZiCore.Loader.SystemLoader.OnStart(MessageDriver.IsMessageServer, platform);
            // using (DBContext context = new DBContext())
            // {
            //     OEMMemberShip.Init(context);
            //     app.AddMessageHandle();
            //     if (MessageDriver.IsMessageServer)
            //     {
            //         app.AddMQHandle();
            //         context.LogMessage("设置为消息服务器", "Init");
            //     }
            // }
        }

        //static MessageHandle DEFAULT_SERVER_HANDLE = (DBContext context) =>
        //    {
        //        List<QQZiFramework.Modals.OEMInfo> oemList;
        //        OEMMemberShip oEMMember = context.Membership as OEMMemberShip;
        //        bool isOemContext = oEMMember != null && oEMMember.OEM != null;
        //        if (!isOemContext)
        //            oemList = OEMMemberShip.OEMList;
        //        else
        //        {
        //            oemList = new List<QQZiFramework.Modals.OEMInfo>();
        //            oemList.Add(((OEMMemberShip)context.Membership).OEM);
        //        }
        //        TriggerMesageSentAvgs avgs = context.GetArgument<TriggerMesageSentAvgs>("TriggerMesageSentAvgs");
        //        foreach (QQZiFramework.Modals.OEMInfo oem in oemList)
        //        {
        //            OEMMemberShip memberShip = OEMMemberShip.GetInstance(oem.Name);
        //            DBContext oemContext;
        //            if (isOemContext) oemContext = context;
        //            else
        //            {
        //                oemContext = memberShip.CreateDBContext();
        //                oemContext.SetArgument("TriggerMesageSentAvgs", avgs);
        //                // new DBContext(null, memberShip.OEM.GetConnectionString(), null, memberShip, args);
        //            }
        //            using (oemContext)
        //            {
        //                MessageDriver.InvokeServerHandle(oemContext, oem.ExtName);
        //            }
        //        }
        //    };

        //public static void AddMessageHandle(this IApplicationBuilder app)
        //{
        //    MessageDriver.RegisterMessageHandle(DEFAULT_SERVER_HANDLE);
        //}

        //public static void AddMQHandle(this IApplicationBuilder app)
        //{
        //    QQZiFramework.MQ.IMQDriver mqInstance = QQZiFramework.MQ.MQDriver.GetInstance();
        //    foreach (QQZiFramework.Modals.OEMInfo oem in OEMMemberShip.OEMList)
        //    {
        //        foreach (Type type in MessageDriver.MQ_Consumers)
        //        {
        //            string queueName = type.Name;
        //            mqInstance.BindReceived(oem.Name + "_" + queueName, (value) =>
        //                {
        //                    int pos = queueName.IndexOf('_');
        //                    string oem = queueName.Substring(0, pos);
        //                    OEMMemberShip memberShip = OEMMemberShip.GetInstance(oem);
        //                    using (DBContext context = memberShip.CreateDBContext())
        //                    {
        //                        BaseBusiness business = context.GetBusiness(type) as BaseBusiness;
        //                        IMQConsumer consumer = business as IMQConsumer;
        //                        consumer.MQ_OnRecive(value);
        //                    }
        //                    return true;
        //                });
        //        }
        //    }
        //}
    }



}